package com.txw.travel.controller.backstage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.txw.travel.bean.PermissionWithStatus;
import com.txw.travel.pojo.Role;
import com.txw.travel.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/backstage/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequestMapping("/all")
    @PreAuthorize("hasAnyAuthority('/role/all')")
    public ModelAndView all(@RequestParam(defaultValue = "1") int index, @RequestParam(defaultValue = "3") int size) {
        Page<Role> rolePage = roleService.getRoleList(index, size);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("roleList", rolePage);

        modelAndView.setViewName("/backstage/role_all");
        return modelAndView;
    }

    @RequestMapping("/add")
    public String add(Role role) {
        roleService.insertRole(role);
        return "redirect:/backstage/role_all";
    }

    @RequestMapping("/edit")
    public ModelAndView edit(Integer rid) {
        Role role = roleService.getRoleById(rid);
        if (role == null)
            return new ModelAndView("redirect:/backstage/role_all");

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("role", role);
        modelAndView.setViewName("/backstage/role_edit");
        return modelAndView;
    }

    @RequestMapping("/update")
    public String edit(Role role) {
        roleService.updateRole(role);
        return "redirect:/backstage/role/all";
    }

    @RequestMapping("/delete")
    public String delete(Integer rid) {
        roleService.deleteRoleById(rid);
        return "redirect:/backstage/role/all";
    }

    @RequestMapping("/setPermission")
    public ModelAndView setPermission(Integer rid) {
        ModelAndView modelAndView = new ModelAndView();
        List<PermissionWithStatus> permissionWithStatusList = roleService.getPermissionWithStatus(rid);
        modelAndView.addObject("rid", rid);
        modelAndView.addObject("permissionWithStatusList", permissionWithStatusList);
        modelAndView.setViewName("/backstage/role_permission");
        return modelAndView;
    }

    @RequestMapping("/updatePermission")
    public String updatePermission(Integer rid, Integer[] pids) {
        roleService.updateRolePermission(rid, pids);
        return "redirect:/backstage/role/all";
    }
}
